package com.zxy.ziems.server.device.service.impl;

import com.zxy.ziems.server.device.convertor.DeviceConvertor;
import com.zxy.ziems.server.device.mapper.DeviceExtendMapper;
import com.zxy.ziems.server.device.pojo.entity.DataTypeEntity;
import com.zxy.ziems.server.device.pojo.entity.DeviceExtendEntity;
import com.zxy.ziems.server.device.pojo.vo.DeviceExtendVO;
import com.zxy.ziems.server.device.service.DataTypeService;
import com.zxy.ziems.server.device.service.DeviceExtendService;
import com.zxy.ziems.server.mybatis.core.query.QueryWrapperX;
import com.zxy.ziems.server.mybatis.core.service.ServiceImplX;
import com.zxy.ziems.server.utils.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DeviceExtendServiceImpl extends ServiceImplX<DeviceExtendMapper, DeviceExtendEntity> implements DeviceExtendService {

    @Autowired
    private DataTypeService dataTypeService;

    @Override
    public Map<String, List<DeviceExtendVO>> getByDeviceIds(List<String> deviceIds) {
        QueryWrapperX<DeviceExtendEntity> query = new QueryWrapperX<>();
        query.lambda().in(DeviceExtendEntity::getDeviceId, deviceIds);
        List<DeviceExtendEntity> maps = this.list(query);
        Map<String, String> typeCodeMap = dataTypeService.listByIdList(maps.stream().map(DeviceExtendEntity::getDataTypeId)
                        .collect(Collectors.toSet()))
                .stream().collect(Collectors.toMap(DataTypeEntity::getId, DataTypeEntity::getCode));
        return maps.stream().map(m -> {
            return DeviceConvertor.INSTANCE.deviceExtendEntity2DeviceExtendVo(m, typeCodeMap.get(m.getDataTypeId()));
        }).collect(Collectors.groupingBy(m -> m.getDeviceId()));
    }

    @Override
    public void insertOrUpdate(DeviceExtendEntity deviceExtendEntity) {
        if (StringUtils.isNotBlank(deviceExtendEntity.getId())) {
            baseMapper.updateById(deviceExtendEntity);
        } else {
            AssertUtil.nonNull(deviceExtendEntity.getDeviceId(), "设备ID，不可为空");
            AssertUtil.nonNull(deviceExtendEntity.getDataTypeId(), "设备属性，不可为空");
            AssertUtil.nonNull(deviceExtendEntity.getDataTypeVal(), "属性值，不可为空");
            QueryWrapperX<DeviceExtendEntity> query = new QueryWrapperX<>();
            query.lambda().eq(DeviceExtendEntity::getDeviceId, deviceExtendEntity.getDeviceId())
                            .eq(DeviceExtendEntity::getDataTypeId, deviceExtendEntity.getDataTypeId());
            DeviceExtendEntity old = baseMapper.selectOne(query);
            if (old != null) {
                old.setDataTypeVal(deviceExtendEntity.getDataTypeVal());
                baseMapper.updateById(old);
            } else {
                baseMapper.insert(deviceExtendEntity);
            }
        }
    }
}
